<template>
	<div class="app-container">
      <el-container>
        <el-aside width="200px">
            <el-card shadow="never" class="envs">
              <div slot="header" class="clearfix">
                  <span>环境列表</span>
              </div>
              <ul>
                <li v-for="item in project.envs" :key="item"
                    :class="{active: item === env}" @click="handleEnv(item)">
                    {{item}}
                </li>
              </ul>
            </el-card>
            <el-card shadow="never">
              <div slot="header" class="clearfix">
                  <span>项目信息</span>
                  <el-button v-if="$store.getters.user.isAdmin || project.role=='OWNER'"
                        icon="el-icon-edit-outline" type="text" @click="handleModifyProject()"></el-button>
              </div>
              <el-form label-position="right" label-width="60px" label-suffix=":">
              	<el-form-item label="编号">
                    <input type="text" class="line-desc ellipsis" disabled :title="project.projectId" :value="project.projectId"></input>
              	</el-form-item>
              	<el-form-item label="描述">
                    <input type="text" class="line-desc ellipsis" disabled :title="project.projectDesc" :value="project.projectDesc"></input>
              	</el-form-item>
              	<el-form-item label="负责人">
                    <input type="text" class="line-desc ellipsis" disabled :title="project.ownerId" :value="project.ownerId"></input>
              	</el-form-item>
              </el-form>
            </el-card>
            <el-card shadow="never" class="teams">
              <div slot="header" class="clearfix">
                  <span>团队成员</span>
                  <el-button v-if="$store.getters.user.isAdmin || project.role=='OWNER'"
                        icon="el-icon-user" type="text" @click="handlePermissionForm()"></el-button>
              </div>
              <ul>
                <li v-for="item in project.userPermissions" :key="item.userId">
                    <div v-if="item.role=='OWNER'" class="role owner">{{item.role}}</div>
                    <div v-else-if="item.role=='PARTNER'" class="role partner">{{item.role}}</div>
                    <div v-else class="role">{{item.role}}</div>
                    <div class="ellipsis" style="width: 85px;">{{item.userId}}</div>
                </li>
              </ul>
            </el-card>
        </el-aside>
        <el-main>
        <div v-if="!project.usable">
            <el-result icon="warning" title="项目已经停止使用"></el-result>
        </div>
        <div v-else>
		<el-form class="filter-container" ref="searchForm" :inline="true">
			<el-row>
                <el-col :span="18">
                    <el-form-item v-if="project.role=='OWNER' || project.role=='PARTNER'">
                        <el-button icon="el-icon-plus" type="success" @click="handleAppend()">添加</el-button>
                    </el-form-item>
                    <!-- <el-form-item>
                        <el-button icon="el-icon-receiving" type="warning" plain @click="handleYamlFormat()">配置整理(慎用)</el-button>
                    </el-form-item> -->
                    <el-form-item>
                        <el-button icon="el-icon-receiving" type="warning" plain @click="handleRecords()">历史记录</el-button>
                    </el-form-item>
                </el-col>
                <el-col :span="6" style="text-align: right;">
                    <el-form-item>
                        <el-button v-if="!yamlMode" icon="el-icon-d-arrow-right" type="text" @click="handleSwitch()" title="switch to yaml source.">Yaml/Source</el-button>
                        <el-button v-else icon="el-icon-d-arrow-left" type="text" @click="handleSwitch()" title="switch to key value format.">Key/Value</el-button>
                    </el-form-item>
                </el-col>
            </el-row>
		</el-form>

        <div v-if="yamlMode" v-loading="listLoading">
            <yaml-editor  v-model="yamlSource" style="height: 450px;"/>
            <el-form v-if="project.role=='OWNER' || project.role=='PARTNER'" class="save-container" ref="saveForm" :inline="true">
                <el-button icon="el-icon-folder" type="primary" @click="handleYamlSave()">保存Yaml</el-button>
                <el-button @click="handleYamlReset()">重置</el-button>
            </el-form>
        </div>
        <div v-else v-loading="listLoading">
            <el-table :data="dataTable.slice((pagination.currentPage-1)*pagination.pagesize, pagination.currentPage*pagination.pagesize)"
                ref="table" :max-height="tableHeight" stripe highlight-current-row border>
                <el-table-column prop="key" label="Key"></el-table-column>
                <el-table-column prop="value" label="Value"></el-table-column>
                <el-table-column label="操作" align="center" width="200" >
                    <template slot-scope="scope">
                        <el-link icon="el-icon-document" type="info" :underline="false" @click="handleRecord(scope.$index,scope.row)">记录</el-link>
                        <el-link v-if="project.role=='OWNER' || project.role=='PARTNER'" icon="el-icon-edit" type="primary" :underline="false" @click="handleModify(scope.$index,scope.row)">修改</el-link>
                        <el-link v-if="project.role=='OWNER' || project.role=='PARTNER'" icon="el-icon-delete" type="warning" :underline="false" @click="handleRemove(scope.$index,scope.row)">移除</el-link>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
              @current-change="handleCurrentChange"
              :current-page="pagination.currentPage"
              :page-size="pagination.pagesize"
              :total="pagination.total"
              background
              layout="total, prev, pager, next">
            </el-pagination>
        </div>
        </div>
      </el-main>
    </el-container>
		<!--信息维护Form-->
		<InfoEditForm :infoDialog="infoDialog" @update="handleSearch('searchForm')"></InfoEditForm>
        <ProjectEditForm :infoDialog="projectDialog" @update="handleProject()"></ProjectEditForm>
        <RecordForm :recordDialog="recordDialog" ></RecordForm>
        <PermissionForm :permissionDialog="permissionDialog" @update="handleProject()" ></PermissionForm>
	</div>
</template>


<script>
    import YamlEditor from '@/components/YamlEditor/Index.vue';
    import ProjectEditForm from "../project/InfoEditForm";
	import InfoEditForm from "./InfoEditForm";
	import PermissionForm from "./PermissionForm";
	import RecordForm from "./RecordForm";

	export default {
		data() {
			return {
				listLoading: false,
				tableHeight: 300,
				searchForm: {},
                projectId: '',
                env: 'def',
                project: {},
                yamlMode: false,
				infoDialog: {
					info: {}
				},
                projectDialog: {
					info: {}
				},
                recordDialog: {
                    row: {},
					info: []
				},
                permissionDialog: {
                    info: []
                },
				pagination: {
					total: 0,
					pagesize: 30,
					currentPage: 1,
				},
                yamlSource: '',
				dataTable: [],
			};
		},
		methods: {
			handleCurrentChange(page) {
				this.pagination.currentPage = page;
			},
			handleSearch() {
                let params = {
                    projectId: this.projectId,
                    env: this.env
                }
                if (this.yamlMode) {
                    this.listLoading = true;
                    this.yamlSource = '';
                    this.$http.fetch(this.api.keyValueYaml, params)
                        .then(data => {
                            this.yamlSource = data;
                            this.listLoading = false;
                        }).catch(err=> {
                            this.listLoading = false;
                        });
                } else {
                    this.listLoading = true;
                    this.$http.fetch(this.api.keyValueItems, params)
                        .then(data => {
                            if (data) {
                                this.pagination.total = data.length;
                                this.dataTable = data;
                            }
                            this.listLoading = false;
                        }).catch(err=> {
                            this.listLoading = false;
                        });
                }
			},
            async handleYamlFormat() {
                let params = {projectId: this.projectId, env: this.env};
                await this.$http.fetch(this.api.keyValueYamlFormat, params);
                this.handleSearch();
                this.$message({ message: '配置YAML格式化完成', type: 'success' });
            },
			handleAppend() {
				this.infoDialog = {
					title: '添加配置',
					visible: true,
					option: 0,
					rowIndex: null,
					projectId: this.projectId,
					env: this.env,
					info: {yamlSource: ''}
				};
			},
			handleModify(index, row) {
				this.infoDialog = {
					title: '修改配置',
					visible: true,
					option: 1,
					rowIndex: index,
					projectId: this.projectId,
					env: this.env,
					info: JSON.parse(JSON.stringify(row))
				};
			},
            async handleRemove(index, row) {
                this.$msgbox({
                	title: '提示',
                	message: '移除配置['+ row.key +'], 是否继续？',
                	showCancelButton: true
                }).then(() => {
                	let params = {projectId: this.projectId, env: this.env, key: row.key};
                    this.$http.fetch(this.api.keyValueRemove, params)
                        .then(data=>{
                            this.$message({ message: '配置移除成功', type: 'success' });
                            this.handleSearch();
                        })
                }).catch(() => {});
            },
            handleSwitch() {
                this.yamlMode = !this.yamlMode;
                this.handleSearch();
            },
            handleEnv(item) {
                this.env = item;
                this.handleSearch();
            },
            handleModifyProject() {
                this.projectDialog = {
                	title: '修改项目',
                	visible: true,
                	option: 1,
                	info: JSON.parse(JSON.stringify(this.project))
                };
            },
            handlePermissionForm() {
                this.permissionDialog = {
                	title: '账号授权',
                	visible: true,
                	option: 1,
                	info: {
                        projectId: this.projectId,
                        env: this.env,
                        userId: '',
                        role: 'PARTNER'
                    }
                };
            },
            async handleYamlSave() {
                let params = {projectId: this.projectId, env: this.env, yamlSource: this.yamlSource, replace: true};
                await this.$http.fetch(this.api.keyValueYamlSave, params);
                this.$message({ message: 'YAML配置保存成功', type: 'success' });
                this.handleSearch();
            },
            handleYamlReset() {
                this.yamlSource = '';
                this.handleSearch();
            },
            async handleRecords() {
                let params = {projectId: this.projectId, env: this.env};
                let data = await this.$http.fetch(this.api.keyValueRecords, params);
                this.recordDialog = {
                	title: '历史记录',
                	visible: true,
                    option: 0,
                    role: this.project.role,
                	info: data
                };
            },
            async handleRecord(index, row) {
                let params = {projectId: this.projectId, env: this.env, key: row.key};
                let data = await this.$http.fetch(this.api.keyValueRecords, params);
                this.recordDialog = {
                	title: '历史记录 Key: '+row.key,
                	visible: true,
                    option: 1,
                    role: this.project.role,
                	rowIndex: index,
                    row: row,
                	info: data
                };
            },
            async handleProject() {
                this.projectId = this.$route.query.projectId;
                let params = {projectId: this.projectId};
                this.project = await this.$http.fetch(this.api.projectInfo, params);

                if (this.project && this.project.usable) {
                    this.handleSearch('searchForm');
                }
            }
		},
		mounted() {
			//默认加载数据
            this.handleProject();

			this.$nextTick(function() {
                let maxheight = window.innerHeight - 128 - 80;
                this.tableHeight = maxheight>300? maxheight: 300;
			});
		},
		components:{
			InfoEditForm,RecordForm,PermissionForm,ProjectEditForm,YamlEditor
		}
	}
</script>
<style scoped>
    .filter-container {
        padding-top: 0px;
    }
    .save-container {
        padding-top: 20px;
    }
    .el-main {
        padding-top: 0px;
    }
    .el-card {
        margin-bottom: 10px;
    }
    .el-card >>> .el-card__header {
        font-size: 16px;
        padding: 10px 20px;
    }
    .el-card >>> .el-card__body {
        font-size: 14px;
        padding: 15px 15px;
    }
    .clearfix:before, .clearfix:after {
        display: table;
        content: "";
      }
    .clearfix:after {
        clear: both
    }
    .el-aside {
        background-color: inherit;
    }
    .el-aside .el-form-item {
       margin-bottom: 0px;
    }
    .el-aside .el-card button {
        font-size: 16px;
        float: right;
        padding: 2px 0px 0px 10px;
    }
    .el-aside .el-form-item .line-desc {
        font-size: 14px;
        border-width: 0px;
        background-color: inherit;
        border-bottom: 1px dotted #666666;
        width: 100px;
    }
    .el-aside .envs >>> .el-card__body {
        padding: 0px;
    }
    .el-aside ul {
        font-size: 14px;
        font-weight: 600;
        list-style-type: none;
        margin-block-start: 0px;
        margin-block-end: 0px;
        margin-inline-start: 0px;
        margin-inline-end: 0px;
        padding-inline-start: 0px;
    }
    .el-aside ul li {
        padding-left: 30px;
        line-height: 40px;
    }
    .el-aside .envs ul li:hover {
        background-color: #b3d8ff;
        color: #FFFFFF;
    }
    .el-aside .envs ul li.active {
        background-color: #66b1ff;
        color: #FFFFFF;
    }
    .el-aside .teams >>> .el-card__body {
        padding: 0px;
    }
    .el-aside .teams ul {
        font-weight: unset;
    }
    .el-aside .teams ul li {
        padding-left: 25px;
        border-bottom: 1px solid #EBEEF5;
    }
    .el-aside .teams ul li .role {
        float: right;
        margin-top: 10px;
        margin-right: 20px;
        line-height: 16px;
        color: #6971a9;
        border: 1px solid #f0f2ff;
        font-size: 12px;
        padding: 1px 3px;
        border-radius: 3px;
    }
    .el-aside .teams ul li .role.owner {
        color: #f56c6c;
        border: 1px solid #fef0f0;
    }
    .el-aside .teams ul li .role.partner {
        color: #e6a23c;
        border: 1px solid #fdf6ec;
    }
</style>
